package org.mzyyn.qr.service.user.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.mzyyn.qr.constants.RedisKeyAppletsConstant;
import org.mzyyn.qr.context.UserAuthContext;
import org.mzyyn.qr.dto.user.Code2sessionLoginDTO;
import org.mzyyn.qr.dto.user.UserProfileLoginDTO;
import org.mzyyn.qr.dto.user.UserRegisterInfoDTO;
import org.mzyyn.qr.entity.UserPO;
import org.mzyyn.qr.mapper.UserMapper;
import org.mzyyn.qr.service.user.UserAppletsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.mzyyn.qr.vo.user.LoginUserInfoVO;
import org.mzyyn.qr.vo.user.LoginUserVO;
import org.mzyyn.qr.vo.user.SessionInfoVO;
import org.mzyyn.qr.vo.user.UserInfoRes;
import org.qr.xiaocao.common.constants.NumberConstant;
import org.qr.xiaocao.common.constants.SqlConstant;
import org.qr.xiaocao.common.enums.CommonResultEnum;
import org.qr.xiaocao.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lipeng
 * @since 2024-06-12
 */
@Service
@Slf4j
public class UserWxAppletsServiceImpl extends ServiceImpl<UserMapper, UserPO> implements UserAppletsService {

    @Autowired
    WxMaService wxMaService;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public UserPO findByUser(String openid) {
        if (StrUtil.isEmpty(openid)) {
            return null;
        }
        LambdaQueryWrapper<UserPO> userQuery = new LambdaQueryWrapper<>();
        userQuery.eq(UserPO::getWxOpenid, openid);
        return this.baseMapper.selectOne(userQuery);
    }

    @Override
    public UserPO checkAndGetUserByLoginPhone() {
        UserPO user = findByUser(UserAuthContext.getUserInfo().getPhone());
        if (null == user) {
            throw new ServiceException(CommonResultEnum.DATA_NOT_BELONG.getCode(), "当前用户不是飞手");
        }
        return user;
    }

    @Override
    public SessionInfoVO appletGetSessionByCode(Code2sessionLoginDTO code2sessionLoginDTO) {
       try {
           WxMaJscode2SessionResult sessionInfo =
                   wxMaService.getUserService().getSessionInfo(code2sessionLoginDTO.getCode());


           if (null == sessionInfo || null == sessionInfo.getOpenid()) {
               log.info("调用微信code2SessionRes失败，error:{}", JSON.toJSONString(sessionInfo));
               throw new ServiceException(CommonResultEnum.REQUEST_OUTSITE_ERROR.getCode(), "调用code登录失败，请稍后重试");
           }

           return BeanUtil.toBean(sessionInfo,SessionInfoVO.class);
       } catch (WxErrorException e) {
           throw new RuntimeException(e);
       }

    }

    @Override
    public UserRegisterInfoDTO getRegisterInfo(UserProfileLoginDTO userProfileLoginDTO) {
        try {
            WxMaJscode2SessionResult codeUserInfo =
                    wxMaService.getUserService().getSessionInfo(userProfileLoginDTO.getCode());
            WxMaPhoneNumberInfo phoneNoInfo =
                    wxMaService.getUserService().getPhoneNoInfo(userProfileLoginDTO.getPhoneCode());
            if (null == phoneNoInfo || StrUtil.isEmpty(phoneNoInfo.getPhoneNumber())) {
                throw new ServiceException(CommonResultEnum.COMMON_FAILED.getCode(), "未获取到手机号");
            }
            String phone = phoneNoInfo.getPhoneNumber();

            UserRegisterInfoDTO userRegisterInfoDTO = new UserRegisterInfoDTO();
            userRegisterInfoDTO.setPhone(phone);
            userRegisterInfoDTO.setUnionid(codeUserInfo.getUnionid());
            userRegisterInfoDTO.setQqopenid(StrUtil.EMPTY);
            userRegisterInfoDTO.setWxopenid(codeUserInfo.getOpenid());
            userRegisterInfoDTO.setUserName(userProfileLoginDTO.getUserName());
            userRegisterInfoDTO.setAvatar(userProfileLoginDTO.getAvatar());

            return userRegisterInfoDTO;

        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }
}
